﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms.Design;
using System.Windows.Media.Imaging;
using MediaPad.Implementation;
using System.ComponentModel;
using System.Drawing.Design;
using MediaPad;

namespace MediaPad.Implementation
{
    internal class ImageFileEditor : FileNameEditor
    {
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService editorService;

            if (context == null || context.Instance == null || provider == null)
                return value;

            try
            {
                // get the editor service, just like in windows forms
                editorService = (IWindowsFormsEditorService)
                   provider.GetService(typeof(IWindowsFormsEditorService));

                System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
                dlg.Filter = InkCanvasAdvUC.DEF_IMAGE_FILTER;
                dlg.CheckFileExists = true;

                BitmapImage im = null;
                string filename = ""; ;
                if (value is BitmapImage)
                {
                    im = value as BitmapImage;
                    filename = im.UriSource.AbsolutePath;
                }
                else
                {
                    filename = (string)value;
                }

                using (dlg)
                {
                    System.Windows.Forms.DialogResult res = dlg.ShowDialog();
                    if (res == System.Windows.Forms.DialogResult.OK)
                    {
                        filename = dlg.FileName;

                        im = new BitmapImage();
                        im.BeginInit();
                        im.UriSource = new Uri(filename);
                        im.CacheOption = BitmapCacheOption.OnLoad;
                        im.EndInit();
                    }
                }
                return im;
            }
            finally
            {
                editorService = null;
            }
        }

        public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        {
            return base.GetPaintValueSupported(context);
        }

        public override void PaintValue(PaintValueEventArgs e)
        {
            BitmapImage im = e.Value as BitmapImage;
            if (im != null)
            {
                string str = im.UriSource.AbsolutePath;
                e.Graphics.DrawString(str, new System.Drawing.Font("Calibri", 14f), new System.Drawing.SolidBrush(System.Drawing.Color.Black),
                    new System.Drawing.PointF(0, 0));

            }
        }
    }
}
